package com.acs.attestation.util;


import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author caoshuan
 * @date 2019-02-26
 * @description 数据填充工具类
 */
@Component
public class FilUtil {

    private static Integer STATUS = 200;
    private static String MESSAGE = "操作成功";

    /**
     * 新增操作时填充实体信息
     */
    public static <T> void fillNewRecord(Object obj, Class<T> objectType) {
        try {
            if (null != obj && null != objectType) {
                setProperty(obj, objectType, "pmCode", UuidUtil.randomUUID());
                //setProperty(obj, objectType, "creator", userPmCode);
                //setProperty(obj, objectType, "createName", userName);
                setProperty(obj, objectType, "createTime", DateUtil.getDateTime());
                setProperty(obj, objectType, "deleted", Boolean.FALSE);
            }
        } catch (Exception e) {
            throw new BusinessException("对象赋值异常");
        }
    }

    /**
     * 修改操作时填充或修改实体信息
     */
    public static <T> void fillModifyRecord(Object obj, Class<T> objectType) {
        try {
            if (null != obj && null != objectType) {
                setProperty(obj, objectType, "modifyTime", DateUtil.getDateTime());
            }
        } catch (Exception e) {
            throw new BusinessException("对象赋值异常");
        }
    }


    private static <T> void setProperty(Object obj, Class<T> objectType, String propertyName, Object value) throws IllegalAccessException, InvocationTargetException {
        PropertyDescriptor property = BeanUtils.getPropertyDescriptor(objectType, propertyName);
        if (null != property) {
            Method readMethod = property.getReadMethod();
            Method writeMethod = property.getWriteMethod();
            if (null != readMethod && null != writeMethod) {
                writeMethod.invoke(obj, value);
            }
        }

    }
}
